<template>
	<view class="coupon-center-container">
		<!-- 自定义导航栏 -->
		<view class="custom-navbar">
			<view class="navbar-left">
				<uni-icons type="left" size="20" @click="goBack"></uni-icons>
			</view>
			<view class="navbar-title">领券中心</view>
			<view class="navbar-right">
				<view class="navbar-actions">
					<uni-icons type="gift" size="20" @click="goToMyCoupons" color="#007AFF" style="margin-right: 20rpx;"></uni-icons>
					<uni-icons type="gear" size="20" @click="showManagementPanel" color="#007AFF" style="margin-right: 20rpx;"></uni-icons>
					<uni-icons type="refresh" size="20" @click="refreshCoupons" style="margin-right: 20rpx;"></uni-icons>
				</view>
			</view>
		</view>
		
		<!-- 优惠券列表 -->
		<view class="coupon-list">
			<view v-if="currentCoupons.length === 0" class="empty-coupons">
				<uni-icons type="gift" size="48" color="#ccc"></uni-icons>
				<text class="empty-text">暂无优惠券</text>
			</view>
			
			<view 
				v-else
				class="coupon-item" 
				v-for="(coupon, index) in currentCoupons" 
				:key="index"
				:class="{ disabled: coupon.isDisabled }"
			>
				<view class="coupon-left">
					<view class="coupon-amount">
						<text class="amount-symbol" v-if="coupon.type !== '折扣券'">¥</text>
						<text class="amount-value">{{ coupon.amount }}</text>
					</view>
					<view class="coupon-condition" v-if="coupon.condition > 0">满{{ coupon.condition }}可用</view>
					<view class="coupon-condition" v-else>无使用条件</view>
				</view>
				<view class="coupon-right">
					<view class="coupon-title">{{ coupon.name || coupon.title }}</view>
					<view class="coupon-desc">{{ coupon.type || coupon.description }}</view>
					<view class="coupon-validity">有效期至：{{ formatDate(coupon.end) || coupon.validity }}</view>
					<view class="coupon-stock" v-if="coupon.originalData && coupon.originalData.size !== undefined">
						<text class="stock-text">库存：{{ coupon.originalData.size }}张</text>
					</view>
					<view class="coupon-status" v-if="coupon.isDisabled">
						<text class="status-text">已领取</text>
					</view>
					<view class="coupon-action">
						<view 
							class="receive-btn" 
							:class="{ 
								disabled: coupon.isDisabled || 
								(coupon.originalData && coupon.originalData.size !== undefined && coupon.originalData.size <= 0)
							}"
							@click="receiveCoupon(coupon)"
						>
							<text class="btn-text">
								{{ 
									coupon.isDisabled ? '已领取' : 
									(coupon.originalData && coupon.originalData.size !== undefined && coupon.originalData.size <= 0) ? '库存不足' : '立即领取'
								}}
							</text>
						</view>
					</view>
				</view>
				<view class="coupon-tag" v-if="coupon.isHot">热</view>
			</view>
		</view>
		
		<!-- 加载更多 -->
		<view v-if="hasMore" class="load-more" @click="loadMoreCoupons">
			<text class="load-more-text">加载更多</text>
		</view>
	</view>
</template>

<script>
	import uniIcons from '@dcloudio/uni-ui/lib/uni-icons/uni-icons.vue';
	import { couponApi } from '@/api/index.js';
	
	export default {
		components: { 
			uniIcons
		},
		data() {
			return {
				userId: 1, // 默认用户ID，实际应该从登录状态获取
				allCoupons: [],
				hasMore: true,
				loading: false,
				useMockData: false
			};
		},
		computed: {
			currentCoupons() {
				return this.allCoupons;
			}
		},
		async mounted() {
			// 确保userId存在
			if (!this.userId) {
				this.userId = 1; // 设置默认值
				console.log('页面加载时设置默认用户ID:', this.userId);
			}
			await this.loadAvailableCoupons();
		},
		onShow() {
			// 页面显示时刷新数据
			this.loadAvailableCoupons();
		},
		methods: {
			// 返回上一页
			goBack() {
				uni.navigateBack();
			},
			
			// 加载可领取的优惠券
			async loadAvailableCoupons() {
				try {
					this.loading = true;
					
					console.log('开始获取可领取优惠券数据...');
					
					// 使用新的API接口获取可领取的优惠券
					const result = await couponApi.getAvailableCoupons();
					
					console.log('可领取优惠券API返回结果:', result);
					console.log('result.code:', result.code);
					console.log('result.data:', result.data);
					console.log('result.msg:', result.msg);
					
					// 检查API响应
					if (result && result.code === 200 && result.data && result.data.length > 0) {
						// 处理优惠券数据，标记已领取状态
						this.allCoupons = await this.processAvailableCoupons(result.data);
						console.log('成功从后端获取可领取优惠券数据，数量:', this.allCoupons.length);
					} else {
						console.log('后端数据获取失败，响应详情:', {
							hasResult: !!result,
							code: result?.code,
							hasData: !!result?.data,
							dataLength: result?.data?.length
						});
						this.allCoupons = [];
						uni.showToast({
							title: '暂无优惠券可领取',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('加载可领取优惠券失败:', error);
					this.allCoupons = [];
					uni.showToast({
						title: '加载失败',
						icon: 'none'
					});
				} finally {
					this.loading = false;
				}
			},
			
			// 转换后端数据格式
			async processAvailableCoupons(backendData) {
				try {
					// 确保userId存在
					if (!this.userId) {
						this.userId = 1; // 设置默认值
						console.log('设置默认用户ID:', this.userId);
					}
					
								// 获取用户已领取的优惠券ID列表（从API和本地存储）
			let userCouponsResult;
			let receivedCouponIds = [];
			
			try {
				userCouponsResult = await couponApi.getUserCoupons(this.userId);
				console.log('用户优惠券API调用成功:', userCouponsResult);
				
				if (userCouponsResult && userCouponsResult.code === 200 && userCouponsResult.data) {
					receivedCouponIds = userCouponsResult.data.map(userCoupon => 
						userCoupon.couponId || userCoupon.coupon_id || userCoupon.id
					);
					console.log('API返回的用户已领取优惠券ID列表:', receivedCouponIds);
				}
			} catch (error) {
				console.log('用户优惠券API调用失败，使用本地存储:', error);
				userCouponsResult = null;
			}
			
			// 如果API调用失败，确保至少显示优惠券（不标记已领取状态）
			if (!userCouponsResult || userCouponsResult.code !== 200) {
				console.log('API调用失败，显示所有优惠券为可领取状态');
				receivedCouponIds = [];
			}
			
			// 强制刷新：每次调用API都重新获取最新状态
			console.log('强制刷新优惠券状态，确保数据同步');
					
					// 从本地存储获取已领取状态（作为备用）
					const localReceivedCoupons = uni.getStorageSync('receivedCoupons') || [];
					receivedCouponIds = [...new Set([...receivedCouponIds, ...localReceivedCoupons])];
					console.log('合并后的已领取优惠券ID列表:', receivedCouponIds);
					
					return backendData.map(coupon => {
						console.log('处理优惠券数据:', coupon);
						console.log('优惠券关键字段:', {
							id: coupon.id,
							name: coupon.name,
							type: coupon.type,
							discount: coupon.discount,
							preferentialMoney: coupon.preferentialMoney || coupon.preferential_money,
							triggerMoney: coupon.triggerMoney || coupon.trigger_money,
							size: coupon.size,
							start: coupon.start || coupon.start_time,
							end: coupon.end || coupon.end_time
						});
						
						// 根据优惠券类型处理显示逻辑
						let amount, condition;
						
						// 支持多种字段名（驼峰和下划线）
						const discount = coupon.discount || 1;
						const preferentialMoney = coupon.preferentialMoney || coupon.preferential_money || 0;
						const triggerMoney = coupon.triggerMoney || coupon.trigger_money || 0;
						const couponType = coupon.type || '满减券';
						
						if (couponType === '折扣券' || discount < 1) {
							// 折扣券：显示折扣信息
							amount = `${Math.round(discount * 10)}折`;
							condition = triggerMoney;
						} else {
							// 满减券：显示优惠金额
							amount = preferentialMoney;
							condition = triggerMoney;
						}
						
						// 检查用户是否已领取过
						const isReceived = receivedCouponIds.includes(coupon.id);
						
						return {
							id: coupon.id,
							name: coupon.name || '优惠券',
							type: couponType,
							amount: amount,
							condition: condition,
							end: coupon.validEnd || coupon.end || coupon.end_time,
							start: coupon.validStart || coupon.start || coupon.start_time,
							isHot: this.isHotCoupon(coupon),
							isDisabled: isReceived,
							originalData: coupon
						};
					});
				} catch (error) {
					console.error('获取用户优惠券状态失败:', error);
					// 如果获取失败，返回原始数据，不标记已领取状态
					return backendData.map(coupon => {
						const discount = coupon.discount || 1;
						const preferentialMoney = coupon.preferentialMoney || coupon.preferential_money || 0;
						const triggerMoney = coupon.triggerMoney || coupon.trigger_money || 0;
						const couponType = coupon.type || '满减券';
						
						let amount, condition;
						if (couponType === '折扣券' || discount < 1) {
							amount = `${Math.round(discount * 10)}折`;
							condition = triggerMoney;
						} else {
							amount = preferentialMoney;
							condition = triggerMoney;
						}
						
						return {
							id: coupon.id,
							name: coupon.name || '优惠券',
							type: couponType,
							amount: amount,
							condition: condition,
							end: coupon.validEnd || coupon.end || coupon.end_time,
							start: coupon.validStart || coupon.start || coupon.start_time,
							isHot: this.isHotCoupon(coupon),
							isDisabled: false, // 默认未领取
							originalData: coupon
						};
					});
				}
			},
			
			// 判断是否为热门优惠券
			isHotCoupon(coupon) {
				// 根据优惠券类型和金额判断是否热门
				const discount = coupon.discount || 1;
				const preferentialMoney = coupon.preferentialMoney || coupon.preferential_money || 0;
				const couponType = coupon.type || '满减券';
				
				if (couponType === '折扣券' || discount < 1) {
					return discount < 0.9; // 9折以下的折扣券算热门
				} else {
					return preferentialMoney >= 20; // 满减20元以上的算热门
				}
			},
			
			// 格式化日期
			formatDate(dateString) {
				if (!dateString) return '';
				try {
					const date = new Date(dateString);
					return date.toLocaleDateString('zh-CN', {
						year: 'numeric',
						month: '2-digit',
						day: '2-digit'
					});
				} catch (error) {
					return dateString;
				}
			},
			
			// 刷新优惠券
			async refreshCoupons() {
				uni.showLoading({ title: '刷新中...' });
				
				try {
					// 重新获取所有数据
					await this.loadAvailableCoupons();
					
					uni.showToast({
						title: '刷新成功',
						icon: 'success'
					});
				} catch (error) {
					console.error('刷新失败:', error);
					uni.showToast({
						title: '刷新失败',
						icon: 'none'
					});
				} finally {
					uni.hideLoading();
				}
			},
			
			// 领取优惠券
			async receiveCoupon(coupon) {
				try {
					// 检查优惠券是否已被领取
					if (coupon.isDisabled) {
						uni.showToast({
							title: '该优惠券已被领取',
							icon: 'none'
						});
						return;
					}
					
					// 检查库存
					if (coupon.size <= 0) {
						uni.showToast({
							title: '优惠券库存不足',
							icon: 'none'
						});
						return;
					}
					
					// 检查是否过期
					const now = new Date();
					const endDate = new Date(coupon.end);
					if (endDate < now) {
						uni.showToast({
							title: '优惠券已过期',
							icon: 'none'
						});
						return;
					}
					
					// 显示确认弹窗
					uni.showModal({
						title: '确认领取',
						content: `确定要领取"${coupon.name}"优惠券吗？`,
						success: async (res) => {
							if (res.confirm) {
								try {
									uni.showLoading({ title: '领取中...' });
									
									// 确保userId存在
									if (!this.userId) {
										this.userId = 1; // 设置默认值
										console.log('设置默认用户ID:', this.userId);
									}
									
									console.log('准备调用领取API，参数:', {
										couponId: coupon.id,
										userId: this.userId,
										coupon: coupon
									});
									
									// 调用领取API
									const result = await couponApi.receiveCoupon(coupon.id, this.userId);
									
									console.log('领取API返回结果:', result);
									console.log('result.code:', result.code);
									console.log('result.data:', result.data);
									console.log('result.msg:', result.msg);
									
									// 检查API响应的详细信息
									if (result) {
										console.log('API响应类型:', typeof result);
										console.log('API响应键:', Object.keys(result));
									}
									
									// 根据你的request.js，API函数直接接收到{code, msg, data}格式
									if (result.code === 200) {
										uni.showToast({
											title: '领取成功',
											icon: 'success'
										});
										
										// 立即更新当前优惠券状态
										coupon.isDisabled = true;
										coupon.status = 'received';
										
										// 将已领取状态保存到本地存储，确保刷新后状态不丢失
										const receivedCoupons = uni.getStorageSync('receivedCoupons') || [];
										if (!receivedCoupons.includes(coupon.id)) {
											receivedCoupons.push(coupon.id);
											uni.setStorageSync('receivedCoupons', receivedCoupons);
										}
										
										// 刷新用户优惠券状态
										await this.loadAvailableCoupons(); // 重新加载可领取优惠券
									} else {
										uni.showToast({
											title: result.msg || '领取失败',
											icon: 'none'
										});
									}
								} catch (error) {
									console.error('领取优惠券失败:', error);
									uni.showToast({
										title: '领取失败，请重试',
										icon: 'none'
									});
								} finally {
									uni.hideLoading();
								}
							}
						}
					});
				} catch (error) {
					console.error('领取优惠券失败:', error);
					uni.showToast({
						title: '领取失败，请重试',
						icon: 'none'
					});
				}
			},
			
			// 加载更多优惠券
			async loadMoreCoupons() {
				if (this.loading) return;
				
				try {
					this.loading = true;
					
					// 这里可以实现分页加载逻辑
					// 暂时只是显示加载状态
					await new Promise(resolve => setTimeout(resolve, 1000));
					
					uni.showToast({
						title: '暂无更多数据',
						icon: 'none'
					});
				} catch (error) {
					console.error('加载更多失败:', error);
				} finally {
					this.loading = false;
				}
			},

			// 跳转到我的优惠券页面
			goToMyCoupons() {
				uni.navigateTo({
					url: '/pages/Coupon/MyCoupons'
				});
			},

			// 显示管理面板 (示例方法，实际需要实现)
			showManagementPanel() {
				uni.showToast({
					title: '管理功能待实现',
					icon: 'none'
				});
			},

			// 显示调试信息
			showDebugInfo() {
				const totalCoupons = this.allCoupons.length;
				const receivedCoupons = this.allCoupons.filter(c => c.isDisabled).length;
				const availableCoupons = totalCoupons - receivedCoupons;
				
				const debugInfo = {
					总优惠券数量: totalCoupons,
					已领取数量: receivedCoupons,
					可领取数量: availableCoupons,
					优惠券详情: this.allCoupons.map(c => ({
						id: c.id,
						name: c.name,
						isDisabled: c.isDisabled,
						size: c.originalData?.size
					}))
				};
				
				uni.showModal({
					title: '调试信息',
					content: JSON.stringify(debugInfo, null, 2),
					showCancel: false
				});
			},

			// 检查用户是否已领取过优惠券
			async checkUserReceivedCoupons() {
				try {
					// 确保userId存在
					if (!this.userId) {
						this.userId = 1; // 设置默认值
						console.log('设置默认用户ID:', this.userId);
					}
					
					const result = await couponApi.getUserCoupons(this.userId);
					
					console.log('用户优惠券检查结果:', result);
					console.log('result.code:', result.code);
					console.log('result.data:', result.data);
					console.log('result.msg:', result.msg);
					
					// 根据你的request.js，API函数直接接收到{code, msg, data}格式
					if (result.code === 200 && result.data && result.data.length > 0) {
						console.log('用户已领取的优惠券:', result.data);
						
						// 标记已领取的优惠券
						const receivedCouponIds = result.data.map(userCoupon => userCoupon.couponId);
						
						this.allCoupons.forEach(coupon => {
							if (receivedCouponIds.includes(coupon.id)) {
								coupon.isDisabled = true;
								coupon.status = 'received';
							}
						});
						
						console.log('已标记已领取的优惠券');
					} else {
						console.log('用户未领取任何优惠券');
					}
				} catch (error) {
					console.error('检查用户优惠券失败:', error);
				}
			},
			
			// 测试API调用
			async testApiCalls() {
				try {
					console.log('=== 开始测试API调用 ===');
					console.log('当前用户ID:', this.userId);
					
					// 测试1：获取可领取优惠券
					console.log('测试1：获取可领取优惠券');
					try {
						const availableResult = await couponApi.getAvailableCoupons();
						console.log('可领取优惠券结果:', availableResult);
					} catch (error) {
						console.error('获取可领取优惠券失败:', error);
					}
					
					// 测试2：获取用户优惠券
					console.log('测试2：获取用户优惠券');
					try {
						const userResult = await couponApi.getUserCoupons(this.userId);
						console.log('用户优惠券结果:', userResult);
					} catch (error) {
						console.error('获取用户优惠券失败:', error);
					}
					
					// 测试3：测试领取优惠券（使用第一个优惠券）
					if (this.allCoupons.length > 0) {
						console.log('测试3：测试领取优惠券');
						const testCoupon = this.allCoupons[0];
						try {
							const testResult = await couponApi.receiveCoupon(testCoupon.id, this.userId);
							console.log('领取测试结果:', testResult);
						} catch (error) {
							console.error('领取测试失败:', error);
						}
					}
					
					console.log('=== API测试完成 ===');
				} catch (error) {
					console.error('API测试失败:', error);
				}
			}
		}
	};
</script>

<style lang="scss" scoped>
	.coupon-center-container {
		background-color: #f5f5f5;
		min-height: 100vh;
	}
	
	// 自定义导航栏
	.custom-navbar {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 44px 16px 12px 16px;
		background-color: #ffffff;
		border-bottom: 1px solid #f0f0f0;
		
		.navbar-left {
			width: 40px;
		}
		
		.navbar-title {
			font-size: 18px;
			font-weight: bold;
			color: #333333;
		}
		
		.navbar-right {
			width: 40px;
			display: flex;
			justify-content: flex-end;
		}
	}
	
	// 优惠券列表
	.coupon-list {
		.empty-coupons {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			padding: 60px 20px;
			
			.empty-text {
				margin-top: 16px;
				font-size: 14px;
				color: #999999;
			}
		}
		
		.coupon-item {
			display: flex;
			background-color: #ffffff;
			margin: 0 16px 12px 16px;
			border-radius: 8px;
			overflow: hidden;
			position: relative;
			
			&.disabled {
				opacity: 0.6;
			}
			
			.coupon-left {
				width: 120px;
				background: linear-gradient(135deg, #ff4757, #ff6b6b);
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				padding: 16px;
				position: relative;
				
				&::after {
					content: '';
					position: absolute;
					right: -8px;
					top: 50%;
					transform: translateY(-50%);
					width: 16px;
					height: 16px;
					background-color: #f5f5f5;
					border-radius: 50%;
				}
				
				.coupon-amount {
					display: flex;
					align-items: baseline;
					margin-bottom: 8px;
					
					.amount-symbol {
						font-size: 16px;
						color: #ffffff;
						font-weight: bold;
					}
					
					.amount-value {
						font-size: 32px;
						color: #ffffff;
						font-weight: bold;
					}
				}
				
				.coupon-condition {
					font-size: 12px;
					color: #ffffff;
					opacity: 0.8;
				}
			}
			
			.coupon-right {
				flex: 1;
				padding: 16px;
				display: flex;
				flex-direction: column;
				justify-content: space-between;
				
				.coupon-title {
					font-size: 16px;
					font-weight: bold;
					color: #333333;
					margin-bottom: 4px;
				}
				
				.coupon-desc {
					font-size: 12px;
					color: #666666;
					margin-bottom: 8px;
				}
				
				.coupon-validity {
					font-size: 12px;
					color: #999999;
					margin-bottom: 12px;
				}
				
				.coupon-stock {
					margin-bottom: 12px;
					.stock-text {
						font-size: 12px;
						color: #999999;
					}
				}
				
				.coupon-status {
					margin-bottom: 12px;
					.status-text {
						font-size: 12px;
						color: #999999;
						background-color: #f0f0f0;
						padding: 4px 8px;
						border-radius: 4px;
						display: inline-block;
					}
				}
				
				.coupon-action {
					.receive-btn {
						background-color: #007AFF;
						padding: 8px 16px;
						border-radius: 20px;
						width: fit-content;
						
						&.disabled {
							background-color: #ccc;
						}
						
						.btn-text {
							font-size: 12px;
							color: #ffffff;
							font-weight: bold;
						}
					}
				}
			}
			
			.coupon-tag {
				position: absolute;
				top: 8px;
				right: 8px;
				background-color: #ff4757;
				color: #ffffff;
				font-size: 10px;
				padding: 2px 6px;
				border-radius: 4px;
			}
		}
	}
	
	// 加载更多
	.load-more {
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 16px;
		background-color: #ffffff;
		
		.load-more-text {
			font-size: 14px;
			color: #007AFF;
		}
	}
</style> 